package com.example.chapter03;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CountServlet",urlPatterns = "/CountServlet")
public class CountServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        int count = 0;
        //将0存入到ServletContext
        this.getServletContext().setAttribute("count", count);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int count = (int) this.getServletContext().getAttribute("count");
        count += 1;
        this.getServletContext().setAttribute("count", count);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<h1>欢迎光临本网站！这是您第"+count+"次访问</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}